package cn.wp.common.core.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * HTTP 输出响应内容工具类
 * 
 * @author chenyb
 *
 */
public class ResponseUtil {

    private static Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    /**
     * 发送HTTP响应信息
     * 
     * @param response HTTP响应对象
     * @param str 信息内容
     * @throws IOException 抛出异常，由调用者捕获处理
     */
    public static void writeString(HttpServletResponse response, String str){
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.write(str);
            writer.flush();
        } catch (IOException ex){
            logger.error("输出字符串出错",ex);
        }
    }

    /**
     * 发送HTTP响应信息,JSON格式
     * 
     * @param response HTTP响应对象
     * @param object 输出对象
     * @throws IOException 抛出异常，由调用者捕获处理
     */
    public static void writeJson(HttpServletResponse response, Object object) {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        try{
            PrintWriter writer = response.getWriter();
            writer.write(mapper.writeValueAsString(object));
            writer.flush();
        }catch (IOException ex){
            logger.error("输出json出错",ex);
        }
    }

    /**
     * 下载文件
     * 
     * @param response HTTP响应对象
     * @throws IOException 抛出异常，由调用者捕获处理
     */
    public static void writeFile(HttpServletResponse response, File file) {
        try{
            String fileName = file.getName();

            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            // 对文件名进行URL转义，防止中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8");

            // 空格用URLEncoder.encode转义后会变成"+"，所以要替换成"%20"，浏览器会解码回空格
            fileName = fileName.replace("+", "%20");

            // "+"用URLEncoder.encode转义后会变成"%2B"，所以要替换成"+"，浏览器不对"+"进行解码
            fileName = fileName.replace("%2B", "+");
            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            byte[] bytes = new byte[in.available()];
            int len = -1;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.flush();
        }catch (IOException ex){
            logger.error("输出文件出错",ex);
        }
    }

    public static void writeImage(HttpServletResponse response,InputStream is){
        OutputStream os = null;
        try{
            // 得到文件大小
            int size = is.available();
            byte[] data = new byte[size];
            is.read(data) ;

            // 设置返回的文件类型
            response.setContentType("image/jpeg");
            os = response.getOutputStream() ;
            os.write(data);
            os.flush();
        }catch (IOException ex){
            logger.error("输出图片出错",ex);
        } finally {
            try {
                if(is != null) {
                    is.close();
                }
                if(os != null ) {
                    os.close();
                }
            } catch (IOException e) {
                logger.error("关闭图片流出错",e);
            }
        }
    }

    public static void writeImage(HttpServletResponse response,File file){
        try {
            writeImage(response,new FileInputStream(file));
        } catch (FileNotFoundException e) {
            logger.error("图片未找到",e);
        }
    }

}